import { ref } from 'vue'
import ArtComments from '@/components/index/artical/artComments.vue'
import ArtCommentSend from '@/components/index/artical/artCommentSend.vue'
import { useRouter, useRoute } from 'vue-router'
import { useCardStore } from '@/stores/cardStore'
import { storeToRefs } from 'pinia'
import { useMainIndexStore } from '@/stores/mainIndexStore'
import { useModalStore } from '@/stores/modalStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useCurrActStroe } from '@/stores/currActStore'
import type { Article, ArticleComments, ErrorData } from '@/types/loginType'
export default function () {
  const { thisArt } = storeToRefs(useCardStore())
  const { changeData } = useModalStore()
  const router = useRouter()
  const route = useRoute()
  const articleId = route.params.id as string
  const goBack = () => {
    router.go(-1)
  }

  const footer = ref(null)

  // 请求获取文章数据
  async function getThisArt(id: string) {
    const { idToArticleAndComments, assignThisArt } = useCardStore()
    const { status, data } = await idToArticleAndComments(id)
    if (status === 200) {
      ;(data as Article).time = new Date((data as Article).time).toLocaleString()
      assignThisArt(data as Article & { contentArr?: string[] })
      const { assignTitle } = useMainIndexStore()
      assignTitle({ msg: '文章', img: (data as Article).mainImg })
    } else {
      changeData({ status: status, data: { msg: (data as ErrorData).msg } })
      router.go(-1)
    }
  }
  const articleComments = ref<ArticleComments[]>([])

  // 请求获取评论
  async function getComments(id: string) {
    const { getComments } = useAsyncAxios()
    const { status, data } = await getComments(id)
    if (status === 200) {
      const result = data as ArticleComments[]
      result.map((comment) => {
        comment.time = new Date(comment.time).toLocaleString()
      })
      articleComments.value = result as ArticleComments[]
    } else {
      changeData({ status: status, data: { msg: (data as ErrorData).msg } })
    }
  }
  // 收藏文章
  async function starAtical() {
    const { currUser } = storeToRefs(useCurrActStroe())
    const { likeArticle } = useAsyncAxios()
    const { status, data } = await likeArticle(currUser.value.id, articleId)
    thisArt.value.isHeart = true
    changeData({ status, data })
  }
  return {
    articleId,
    thisArt,
    footer,
    articleComments,
    getComments,
    goBack,
    getThisArt,
    starAtical,
    ArtComments,
    ArtCommentSend
  }
}
